package com.livesource.client.webservices.github;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.livesource.client.model.entry.ProjectClass;

/**
 * Communicates via REST Web Service
 * 
 * @Architecture
 */
public class RequestGitListFiles {

	// https://api.github.com/repos/allineo/TravelLog/git/trees/master

	private static String url = "https://api.github.com/repos/";

	public static void getJsonpRequest(final String panelSelected,
			final String projectURL) {

		JsonpRequestBuilder jsonp = new JsonpRequestBuilder();

		jsonp.setTimeout(30000);

		String urlList = url + projectURL + "/git/trees/master";

		jsonp.requestObject(urlList, new AsyncCallback<JavaScriptObject>() {

			public void onFailure(Throwable throwable) {

				System.out.println("Error: " + throwable);
				Window.alert(throwable.toString());
			}

			public void onSuccess(JavaScriptObject feed) {

				JSONObject objFeed = new JSONObject(feed);

				JSONObject objData = (JSONObject) objFeed.get("data");

				JSONArray objTreeArray = objData.get("tree").isArray();

				for (int i = 0; i < objTreeArray.size(); i++) {

					JSONObject objTree = (JSONObject) objTreeArray.get(i);

					ProjectClass projectEntry = ConvertGithubToProjectEntry
							.convertJsonp(objTree);

					String objPath = objTree.get("path").isString()
							.stringValue();

					System.out.println("objPath: " + objPath);
				}

			}
		});
	}
}
